$(document).ready(function () {
    var that = this;

    var taskArr = ['checkin', 'invite', 'sendStory'];

    var $singleTaskModal = null,
        $singleTaskModalContent = null,
        $singleTaskModalBtn = null,
        currentSingleTask = null;

    var $taskModal;

    var userId = $(document.body).attr('data-userid');

    var taskFunctionMap = {
        // follow: '关注我们空间可再获100积分。',
        invite: function (next) {
            fusion2.dialog.invite({
                msg: "一起来选购吧~",
                source: userId,
                onSuccess: function (opt) {
                    invite(opt.invitees.length, function () {
                        /*next && setTimeout(function () {
                            goToNextTask();
                        }, 500);*/
                    });
                },
                onCancel: function (opt) {
                    next && goToNextTask();
                },
                onClose: function (opt) {
                    next && goToNextTask();
                }
            });
        },
        sendStory: function (next) {
            fusion2.dialog.sendStory({
                title: "亲爱的，我发现一条超美的裙子！",
                img: "./icons/ap.png",
                summary: "2013最流行的搭配推荐！姐妹们每天打扮用来参考的秘密武器！衣衣、裙子、包包、美鞋，你一定会喜欢的！",
                msg: "一起来选购吧",
                source: userId,
                onSuccess: function (opt) {
                    next && sendStory(opt.invitees.length, function () {
                        /*setTimeout(function () {
                            goToNextTask();
                        }, 500);*/
                    });
                },
                onCancel: function (opt) {
                    next && goToNextTask();
                },
                onClose: function (opt) {
                    next && goToNextTask();
                }
            });
        }
    };

    $('#do-tasks').click(function (ev) {
        ev.preventDefault();

        // 弹出做任务界面
        showTaskBoard();
    });

    // 领取积分按钮
    var $checkInBtn = $('#checkin-btn');
    $checkInBtn.click(function (ev) {
        ev.preventDefault();

        if (!$(ev.target).hasClass('disabled')) {
            checkIn(function () {
                $checkInBtn.addClass('disabled');
                $('#task-checkin .task-btn').addClass('task-btn-disabled');
                hideAlert();
                showTaskBoard();
            });
        }
    });

    // 喜欢、收藏
    $('.item-like, .item-collect').each(function (index) {
        var $target = $(this),
            $link = $target.find('a'),
            $item = $target.parents('.item'),
            paramArr = [];

        $.each({
            url: location.href,
            desc: getRidOfSpace($item.find('.item-desc').text()),
            title: getRidOfSpace($item.find('.item-hd').text()),
            pics: $item.find('.item-pic img').prop('src'),
            summary: ' '
        }, function (key, value) {
            paramArr.push(key + '=' + encodeURIComponent(value));
        });

        $.each(paramArr, function (index, el) {
            console.log(decodeURIComponent(el));
        });

        $link.click(function (ev) {
            ev.preventDefault();

            window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?' + paramArr.join('&'), '_blank', 'scrollbars=no,width=600,height=560,left=175,top=70,status=no,resizable=yes');

            if ($target.hasClass('item-like')) {
                like($item.attr('data-id'), function (data) {
                    $link.next('.count').html(data.count);
                });
            } else if ($target.hasClass('item-collect')) {
                collect($item.attr('data-id'), function (data) {
                    $link.next('.count').html(data.count);
                });
            }
        });
    });

    // 购买链接
    $('.item-pic a, .item-buy a, #search-bar a').click(function (ev) {
        ev.preventDefault();
        ev.stopPropagation();

        openLink(this.href);
    });

    // 积分兑换按钮
    $('#exchange-gifts').click(function (ev) {
        ev.preventDefault();

        alertInfo('敬请期待！');
    });

    function initializeSingleTaskModal () {
        if ($singleTaskModal) {
            return;
        }

        $singleTaskModal = $('#single-task-modal');
        $singleTaskModal.jqm({
            closeClass: 'modal-close',
            modal: true
        });

        $singleTaskModalContent = $singleTaskModal.find('.modal-bd-content');
        $singleTaskModalBtn = $singleTaskModal.find('.modal-ft a');

        $singleTaskModalBtn.click(function (ev) {
            ev.preventDefault();

            currentSingleTask && currentSingleTask();
        });
    }

    function checkIn (callback) {
        // 调用签到接口
        $.ajax({
            url: './abtainPoints.htm?task_id=3&userid=' + userId,
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                // 领取成功
                if (data) {
                    alertSuccess('签到成功，成功获取' + data.points + '积分！');
                    callback();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // 领取失败
                alertError(textStatus);
            },
            complete: function (jqXHR, textStatus) {

            }
        });
    }

    function like (itemId, callback) {
        // 喜欢任务
        $.ajax({
            url: './abtainPoints.htm?task_id=1&userid=' + userId + '&item_id=' + itemId,
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                // 成功
                callback && callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // 失败
                alertError(textStatus);
            },
            complete: function (jqXHR, textStatus) {

            }
        });
    }

    function collect (itemId, callback) {
        // 收藏任务
        $.ajax({
            url: './abtainPoints.htm?task_id=2&userid=' + userId + '&item_id=' + itemId,
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                // 成功
                callback && callback(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // 失败
                alertError(textStatus);
            },
            complete: function (jqXHR, textStatus) {

            }
        });
    }

    function invite (num, callback) {
        // 邀请任务
        $.ajax({
            url: './abtainPoints.htm?task_id=7&userid=' + userId + '&num=' + count,
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                // 领取成功
                alertSuccess('邀请' + num + '人成功，成功获取' + data.points + '积分！');
                callback && callback();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // 领取失败
                alertError(textStatus);
            },
            complete: function (jqXHR, textStatus) {

            }
        });
    }

    function sendStory (callback) {
        // 分享应用任务
        $.ajax({
            url: './abtainPoints.htm?task_id=8&userid=' + userId,
            dataType: 'json',
            cache: false,
            success: function (data, textStatus, jqXHR) {
                // 领取成功
                if (data.success) {
                    alertSuccess('分享应用成功，成功获取' + data.points + '积分！');
                    callback && callback();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // 领取失败
                alertError(textStatus);
            },
            complete: function (jqXHR, textStatus) {

            }
        });
    }

    function saveBlog (title, content, onSuccess) {
        fusion2.dialog.saveBlog({
            title: title,
            content: content,
            context: "",
            onSuccess: function (opt) {
                onSuccess && onSuccess();
                goToNextTask();
            },
            onCancel: function (opt) {
            },
            onClose: function (opt) {
            }
        });
    }

    function goToNextTask () {
        // TODO
        // 调用查看下一个任务
        // var taskName = 'invite';
        var taskName = 'sendStory';

        hideAlert();

        initializeSingleTaskModal();

        $singleTaskModalContent.html(window.taskContentMap[taskName]);

        currentSingleTask = taskFunctionMap[taskName];

        $singleTaskModal.jqmShow();
    }

    function alertSuccess (msg) {
        fusion2.ui.showMsgbox({
            type: 2,
            msg: msg,
            timeout: 50000
        });
    }

    function alertError (msg) {
        fusion2.ui.showMsgbox({
            type: 3,
            msg: msg,
            timeout: 50000
        });
    }

    function alertLoading () {
        fusion2.ui.showMsgbox({
            type: 4,
            msg: '请稍候...',
            timeout: 50000
        });
    }

    function alertInfo (msg) {
        fusion2.ui.showMsgbox({
            type: 1,
            msg: msg,
            timeout: 2000
        });
    }

    function hideAlert () {
        fusion2.ui.hideMsgbox();
    }

    function getRidOfSpace (str) {
        return str.replace(/\s/g, '');
    }

    function openLink (url) {
        fusion2.nav.open({
            url: url
        });
    }

    function showTaskBoard () {
        if (!$taskModal) {
            $taskModal = $('#multi-tasks-modal');
            $taskModal.jqm({
                trigger: $('#do-tasks'),
                closeClass: 'modal-close',
                modal: true
            });

            $('#task-checkin .task-btn').click(function (ev) {
                var $target;

                ev.preventDefault();

                $target = $(ev.target);

                if (!$target.hasClass('task-btn-disabled')) {
                    checkIn(function () {
                        $target.addClass('task-btn-disabled');
                        $checkInBtn.addClass('disabled');
                        setTimeout(function () {
                            hideAlert();
                        }, 500);
                    });
                }
            });
            $('#task-invite .task-btn').click(function (ev) {
                var $target;

                ev.preventDefault();

                $target = $(ev.target);

                if (!$target.hasClass('task-btn-disabled')) {
                    taskFunctionMap.invite(function () {
                        $target.addClass('task-btn-disabled');
                    });
                }
            });
            $('#task-sendstory .task-btn').click(function (ev) {
                var $target;

                ev.preventDefault();

                $target = $(ev.target);

                if (!$target.hasClass('task-btn-disabled')) {
                    taskFunctionMap.sendStory(function () {
                        $target.addClass('task-btn-disabled');
                    });
                }
            });
        }

        $taskModal.jqmShow();
    }
});